package com.sdx.third;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.sdx.service.ConfigService;

import java.io.File;

/**
 * @ClassName AliOSSApi
 * @Description: 阿里云对象管理api
 * @author: tanbaocai
 * @date: 2019/1/17 16:17
 */
public class AliOSSApi {

	public static String accessKeyId;
	public static String accessKeySecret;
	public static String endPoint;
	static {
		accessKeyId = ConfigService.ossKeyId;
		accessKeySecret = ConfigService.ossKeySecret;
		endPoint = ConfigService.ossEndPoint;
	}
	/**
	 * 上传本地文件
	 * @param localFile 本地文件路径
	 * @param bucketName
	 * @param filePath objectName
	 * @return
	 */
	public static void uploadLocalFile(String localFile,String bucketName,String filePath) {

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

		// 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
		PutObjectResult objectResult = ossClient.putObject(bucketName, filePath, new File(localFile));
		// 关闭OSSClient。
		ossClient.shutdown();
	}

	public static void main(String[] args) {
		uploadProject("Z:\\gkzw","gkzw");
	}

	public static void uploadProject(String path,String subPath) {
		File dir = new File(path);
		OSSClient ossClient = new OSSClient("http://oss-cn-beijing.aliyuncs.com", "LTAIvuh1aHC2UJEi", "ekFxGw4gRzHKxDYYmGC2MAnz9r1Pdg");
		parseFile(ossClient,dir,subPath,"sdxpro");
		ossClient.shutdown();
	}

	public static void parseFile(OSSClient ossClient,File file,String subPath,String bucketName) {
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				parseFile(ossClient,files[i],subPath,bucketName);
			}
		} else {
			String filePath = file.getPath();
			filePath = filePath.substring(filePath.lastIndexOf(subPath)).replaceAll("\\\\","/");
			ossClient.putObject(bucketName,filePath,file);
		}
	}
}
